package xunmeng.web.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/checkcodeservlet")
public class checkcodeservlet extends HttpServlet {//将验证码输出到浏览器
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.创建一个图片对象（验证码图片对象）
            //定义图片的宽高
        int width=100;
        int height=50;
            //创建一张图片
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

        //2.美化验证码
            //创建该图片的画笔
        Graphics g=image.getGraphics();
            //填充图片颜色
        g.setColor(Color.PINK);
        g.fillRect(0,0,width,height);
            //设置边框
        g.setColor(Color.BLUE);
        g.drawRect(0,0,width-1,height-1);
            //增加文字
        g.setColor(Color.BLUE);
        String str="ABCDEFGHIGKLMNOPQRSTWVUXYZabcdefghijklmnopqrstuwvxyz0123456789";
        Random random=new Random();
        StringBuilder stringBuilder=new StringBuilder();
        for (int i=1;i<=4;i++) {
            int index = random.nextInt(str.length());
            char s = str.charAt(index);
            stringBuilder.append(s);
            g.drawString(s+"",width/5*i,height/2);
        }
        req.getSession().setAttribute("checkcode",stringBuilder.toString());
            //画干扰线
        g.setColor(Color.GREEN);
        for(int i=1;i<=10;i++){
            int x1=random.nextInt(width);
            int x2=random.nextInt(width);
            int y1=random.nextInt(height);
            int y2=random.nextInt(height);
            g.drawLine(x1,y1,x2,y2);
        }
        //3.将验证码图片输出到浏览器
        ImageIO.write(image,"jpg",resp.getOutputStream());

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
